package com.hhss.qishi.entity.system;

import com.fasterxml.jackson.annotation.JsonIgnore;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * security 权限验证用户
 * @author Administrator
 *
 */
public class UserSecurity extends User implements UserDetails{
	
	private static final long serialVersionUID = -2098026356652295278L;

	public UserSecurity(User user) {
        if (user != null) {
            this.setUuid(user.getUuid());
            this.setUserName(user.getLoginId());
            this.setPassword(user.getPassword());
            this.setLoginId(user.getLoginId());
            this.setEmail(user.getEmail());
            this.setPhone(user.getPhone());
			this.setSalt(user.getSalt());
			this.setSpec(user.getSpec());
            this.setCreateUser(user.getCreateUser());
            this.setCreateTime(user.getCreateTime());
            this.setLastUpdateUser(user.getLastUpdateUser());
            this.setLastUpdateTime(user.getLastUpdateTime());
            this.setRoles(user.getRoles());
        }
    }
	
	/**
	 * 设置角色名称前缀ROLE_
	 */
	@Override
	@JsonIgnore
	public Collection<? extends GrantedAuthority> getAuthorities() {
		List<GrantedAuthority> authorities = new ArrayList<>();
		if(!CollectionUtils.isEmpty(getRoles())) {
			for (Role role : getRoles()) {
				if(role != null){
					// authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getRoleCode()));
					for(Permission pms : role.getPermissions()){
						// 角色code和权限操作组成认证，如：role_input
						authorities.add(new SimpleGrantedAuthority(String.format("%s-%s", role.getRoleCode(),
								pms.getPermissionText())));
					}
				}
			}
		}
		return authorities;
	}

	@Override
	public String getUsername() {
		return getLoginId();
	}
	
	/**
	 * 帐户是否过期
	 */
	@Override
	public boolean isAccountNonExpired() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean isAccountNonLocked() {
		// TODO Auto-generated method stub
		return false;
	}
	
	/**
	 * 帐户密码是否过期，一般有的密码要求性高的系统会使用到，比较每隔一段时间就要求用户重置密码
	 */
	@Override
	public boolean isCredentialsNonExpired() {
		// TODO Auto-generated method stub
		return false;
	}
	
	/**
	 * 帐号是否可用
	 */
	@Override
	public boolean isEnabled() {
		return getStatus() == 1 ? true : false;
	}
}
